package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.config.OssAliyunConfigProperties;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource(name = "OSSAliyunFileStorageService")
    FileStorageService fileStorageService;  // OSS

    @Autowired
    OssAliyunConfigProperties properties;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;


    @Value("${file.oss.profix}")
    private String profix;

    /**
     * 分页查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listPage(WmMaterialDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 分页
        dto.checkParam();

        //2 构建条件 执行查询
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        //封装条件
        //收藏
        if (dto.getIsCollection() != null && dto.getIsCollection()==1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //查询当前登录人的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user != null) {
            wrapper.eq(WmMaterial::getUserId, user.getId());
        }

        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);


        IPage<WmMaterial> ipage = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> pageResult = page(ipage, wrapper);

        // 图片回显
//        List<WmMaterial> materialList = pageResult.getRecords();
//        for (WmMaterial wmMaterial : materialList) {
//            wmMaterial.setUrl(properties.getWebSite() + wmMaterial.getUrl());
//        }
        // JDK stream 流（学习JDK8新特性）
        List<WmMaterial> materialList =
                pageResult.getRecords().stream()  // 转成流
                .map(wmMaterial -> {
                    wmMaterial.setUrl(properties.getWebSite() + wmMaterial.getUrl());
                    return wmMaterial;
                })  // 中间处理过程
                .collect(Collectors.toList());  // 转数据集合
        //3 返回结果（图片回显）
        return new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), materialList);
    }

    /**
     * 上传图片接口
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(@RequestParam("multipartFile") MultipartFile multipartFile) {
        //1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            //2 上传图片OSS
            String originalFilename = multipartFile.getOriginalFilename(); // 原始文件名称
            // 重命名
            // 文件名称
            String name = UUID.randomUUID().toString().replace("-", "");
            // 文件后缀 .png .jpg .avi
            String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = name + postFix;
            String fileUrl = fileStorageService.store(profix, filename, multipartFile.getInputStream());

            //3 保存上传记录数据库
            WmMaterial wmMaterial = WmMaterial.builder()
                                    .createdTime(new Date())
                                    .isCollection(0)
                                    .type(0)
                                    .url(fileUrl)
                                    .build();
            // 登录自媒体人的用户id
            WmUser user = WmThreadLocalUtils.getUser();
            if (user != null) {
                wmMaterial.setUserId(user.getId());
            }
            save(wmMaterial);

            //4 返回结果（图片需要回显）
            wmMaterial.setUrl(properties.getWebSite() + fileUrl);
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
    /**
     * 删除图片素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //1.参数校验
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询当前图片是否存在
        WmMaterial wmMaterial= super.getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询当前图片是否被引用
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);//被引用的次数
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.File_EXIST);
        }
        //4.执行删除
        fileStorageService.delete(wmMaterial.getUrl());//删除OSS里面的素材
        super.removeById(id);//删除素材
        //5.返回结果

        return ResponseResult.okResult();
    }

    /**
     * 收藏和取消图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id,Short type) {
        //1.参数校验
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //.执行收藏或取消收藏（当前用户）
        Integer useId = WmThreadLocalUtils.getUser().getId();//自媒体用户ID
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmMaterial::getUserId,useId)
                .eq(WmMaterial::getId,id);
        WmMaterial wmMaterial = super.getOne(wrapper);
        wmMaterial.setIsCollection(type.intValue());
        super.updateById(wmMaterial);
        //返回结果
        return ResponseResult.okResult();
    }
}
